<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue3-escook</title>
  <link rel="stylesheet" href="./lib/style.css">
  <script type="importmap">
    {
      "imports" : {
        "vue": "./lib/vue-3.5.0.js"
      }
    }
  </script>
  <script type="module">
    import { createApp, useTemplateRef } from 'vue'

    // 在 vue 中，自定义 hook 就是一个函数，只不过函数必须以 use 开头
    const useInput = (refName) => {
      const usernameRef = useTemplateRef(refName)

      const setValueAndFocus = (defaultValue) => {
        usernameRef.value.value = defaultValue
        usernameRef.value.focus()
      }

      return {
        setValueAndFocus
      }
    }

    const app = createApp({
      setup() {
        const usernameRef = useInput('username')
        const introRef = useInput('intro')

        return {
          usernameRef,
          introRef
        }
      }
    })

    app.mount('#app')
  </script>
</head>

<body>
  <div id="app">
    <button @click="usernameRef.setValueAndFocus('liulongbin')">让文本框获取焦点并设置默认值</button>
    <input type="text" ref="username">
    <hr>
    <button @click="introRef.setValueAndFocus('escook')">让 textarea 获取焦点并设置默认值</button>
    <textarea ref="intro"></textarea>
  </div>
</body>

</html>